<template>
  <div ref="chartRef" style="width: 600px; height: 400px;"></div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';
import {appointmentCountByDateDay} from "@/api/appointment.js";

const chartRef = ref(null);
let chartInstance = null;

// 生成最近7天日期
function generateLast7Days() {
  const dates = [];
  for (let i = 6; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(date.toISOString().split('T')[0]);
  }
  return dates;
}

// 处理原始数据
function processData(originalData) {
  const dateMap = new Map();
  const sevenDays = generateLast7Days();

  // 初始化7天数据为0
  sevenDays.forEach(date => {
    dateMap.set(date, 0);
  });

  // 填充已有数据
  originalData.forEach(item => {
    if (dateMap.has(item.appoint_date)) {
      dateMap.set(item.appoint_date, item.count);
    }
  });

  return Array.from(dateMap).map(([date, count]) => ({
    date,
    count
  }));
}

// 图表配置
function getChartOption(processedData) {
  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: processedData.map(item => item.date),
      axisLabel: {
        formatter: value => value.split('-').slice(1).join('-')
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: processedData.map(item => item.count),
      type: 'line',
      smooth: true,
      // 移除了 areaStyle 配置
      itemStyle: {
        color: '#5470C6' // 可选：自定义线条颜色
      }
    }],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  };
}

// 初始化图表
const initChart = async () => {
  if (!chartRef.value) return;
  const res = await appointmentCountByDateDay();
  // 原始数据（替换成props接收实际数据）
  const originalData = res.data

  const processedData = processData(originalData);

  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption(getChartOption(processedData));
}

// 响应式调整
function resizeChart() {
  chartInstance?.resize();
}

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
});
</script>
